package com.hyy.blogtest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyy.blogtest.common.advice.ResponseAdvice;
import com.hyy.blogtest.common.exception.BlogException;
import com.hyy.blogtest.common.exception.UserException;
import com.hyy.blogtest.common.pojo.dadaobject.BlogInfo;
import com.hyy.blogtest.common.pojo.dadaobject.UserInfo;
import com.hyy.blogtest.common.pojo.request.RegisterRequest;
import com.hyy.blogtest.common.pojo.request.UserLoginRequest;
import com.hyy.blogtest.common.pojo.response.RegisterResponse;
import com.hyy.blogtest.common.pojo.response.UserInfoResponse;
import com.hyy.blogtest.common.pojo.response.UserLoginResponse;
import com.hyy.blogtest.common.utils.BeanUtilsConver;
import com.hyy.blogtest.common.utils.JwtUtil;
import com.hyy.blogtest.common.utils.SecurityUtil;
import com.hyy.blogtest.mapper.BlogInfoMapper;
import com.hyy.blogtest.mapper.UserInfoMapper;
import com.hyy.blogtest.service.UserService;
import io.jsonwebtoken.Jwt;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource(name = "userInfoMapper")
    private UserInfoMapper userInfoMapper;

    @Resource(name="blogInfoMapper")
    private BlogInfoMapper blogInfoMapper;

//    @Autowired
//    private ResponseAdvice responseAdvice;

    @Override
    public UserInfoResponse selectById(Integer id) {
        UserInfo userInfo = userInfoMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getDeleteFlag, 0)
                        .eq(UserInfo::getId, id)
        );

        //如果没有找到返回的null
        UserInfoResponse userInfoResponse = BeanUtilsConver.converToUser(userInfo);
        return userInfoResponse;
    }

    /*
    * 没有查到用户名，或者输入密码错误，抛出异常
    * 正确返回登陆响应
    * */
    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {

        //从数据库获取用户信息，根据用户名
        UserInfo userInfo = userInfoMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getDeleteFlag, 0)
                        .eq(UserInfo::getUserName, userLoginRequest.getUsername())
        );
        if (userInfo == null) {
            log.error("没有查询到名为：{}，的用户", userLoginRequest.getUsername());
            log.info("\n");
            log.info("\n");
            log.info("\n");
            log.info("\n");
            throw new UserException("没有查询到名为：" + userLoginRequest.getUsername() + "，的用户");
        }
        log.error(userInfo.getPassword());
        log.info("\n");
        log.info("\n");
        log.info("\n");
        log.info("\n");

        if (!SecurityUtil.verify(userLoginRequest.getPassword(), userInfo.getPassword())) {
            //log自动换行
            log.error("密码不正确：用户密码：{}", userLoginRequest.getUsername());
            log.error("数据库加密密码：{}", userInfo.getPassword());
            throw new UserException("用户密码输入错误");
        }

        //用户密码正确
        UserLoginResponse userLoginResponse = new UserLoginResponse();


        //这个响应有两个字段，先把用户id设置
        userLoginResponse.setUserId(userInfo.getId());

        //设置token

            //设置载荷
        Map<String,Object> map = new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("username",userLoginRequest.getUsername());
        userLoginResponse.setToken(JwtUtil.getToken(map));

        return userLoginResponse;



    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {

        //找到这个博客信息，根据id
        BlogInfo blogInfo=null;
        try{
            blogInfo=blogInfoMapper.selectById(blogId);
            if(blogInfo==null){
                throw new BlogException("前端的blogId，在数据库中不存在");
            }
        }catch (Exception e){
            log.error("根据博客id，在数据库查找博客失败，{}",e.getMessage());
            throw new BlogException(e.getMessage());
        }


        //根据博客信息找到作者id,
        int userId=blogInfo.getUserId();

        // 根据作者id找到作者信息
        //找到这个博客信息，根据id
        UserInfo userInfo=null;
        try{
            userInfo=userInfoMapper.selectById(userId);
            if(userInfo==null){
                throw new BlogException("userId在数据库中不存在，分析一下获取的userId是否有问题");
            }
        }catch (Exception e){
            log.error("根据userId，在数据库查找用户信息失败，{}",e.getMessage());
            throw new UserException(e.getMessage());
        }
        return BeanUtilsConver.converToUser(userInfo);
    }

    @Override
    public RegisterResponse register(RegisterRequest request) {
        UserInfo userInfo=BeanUtilsConver.conver(request);
        String sqlPassword=SecurityUtil.encryptPassword(userInfo.getPassword());
        userInfo.setPassword(sqlPassword);
        int result=0;
        try{
            result=userInfoMapper.insert(userInfo);
        }catch (Exception e){
            log.error("数据库插入新用户（注册）失败：{}",e.getMessage());
            throw new UserException("注册失败："+e.getMessage());
        }
        if(result==0){
            return new RegisterResponse(false,"没有插入新用户，但是也没有报错");
        }
        return new RegisterResponse(true,"");
    }

}
